package com.yunhe.authority.service.company.impl;

import com.github.stuxuhai.jpinyin.PinyinException;
import com.github.stuxuhai.jpinyin.PinyinHelper;
import com.yunhe.authority.domain.authority.RealStation;
import com.yunhe.authority.domain.authority.Role;
import com.yunhe.authority.domain.authority.Station;
import com.yunhe.authority.domain.authority.User;
import com.yunhe.authority.domain.company.Company;
import com.yunhe.authority.domain.company.CompanySupportingInfo;
import com.yunhe.authority.domain.company.ContractAccessories;
import com.yunhe.authority.domain.office.Office;
import com.yunhe.authority.model.CompanyUpload;
import com.yunhe.authority.model.OfficeManageCompanyInfoVO;
import com.yunhe.authority.model.poi.CompanyPoi;
import com.yunhe.authority.repository.company.CompanyCrudRepository;
import com.yunhe.authority.repository.company.CompanyRepository;
import com.yunhe.authority.service.authority.*;
import com.yunhe.authority.service.company.CompanyService;
import com.yunhe.authority.service.company.CompanySupportingInfoService;
import com.yunhe.authority.service.company.PaymentInfoService;
import com.yunhe.authority.service.office.OfficeService;
import com.yunhe.authority.util.ExcelUtils;
import com.yunhe.authority.util.PoiUtils;
import com.yunhe.common.constant.OfficeConts;
import com.yunhe.common.exception.ArgumentErrorException;
import com.yunhe.common.exception.ModelNotFoundException;
import com.yunhe.common.exception.ObjectNotFoundException;
import com.yunhe.common.exception.UniqueConstraintsException;
import com.yunhe.common.filter.ServerContextHolder;
import com.yunhe.common.model.PageParam;
import com.yunhe.common.util.DateTimeUtils;
import com.yunhe.common.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import com.yunhe.common.util.CollectionUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author liuronglei
 */
@Service
@Slf4j
public class CompanyServiceImpl implements CompanyService {
    @Autowired
    private CompanyRepository companyrepository;
    @Autowired
    private StationService stationService;

    @Autowired
    private OfficeService officeService;
    @Autowired
    private CompanyCrudRepository companyCrudRepository;

    @Autowired
    private RealStationService realStationService;

    @Autowired
    private UserService userService;

    @Autowired
    private PaymentInfoService paymentInfoService;

    @Autowired
    private CompanySupportingInfoService companySupportingInfoService;

    @Autowired
    private CompanyRoleService companyRoleService;

    @Override
    public List<Company> findByStationId(Long stationId) {
        return companyrepository.findByStationId(stationId);
    }

    @Override
    public List<Company> findByFirmId(Long firmId) {
        return companyrepository.findByFirmId(firmId);
    }

    /**
     * 企业对象处理和判断
     * @param company 企业对象
     */
    private void processBeforeSave(Company company, Long stationId)
            throws ArgumentErrorException, UniqueConstraintsException, ObjectNotFoundException {

        //判断企业代码、企业名称是否为空
        if (StringUtil.isEmpty(company.getTitle())) {
            throw new ArgumentErrorException("企业代码");
        }

        //判断电站下企业名称是否重复
        Company companyByTitle;

        //企业状态 在园
        String companyStatus = "0";

        if (company.getId() == null) {
            companyByTitle = companyCrudRepository.findByRealStationIdAndTitle(stationId, company.getTitle());
            if (companyByTitle != null  && companyStatus.equals(companyByTitle.getCompanyStatus())) {
                throw new UniqueConstraintsException("已存在名称为" + company.getTitle() + "的企业");
            }
        } else if (company.getId() != null) {
            companyByTitle = companyCrudRepository.findByRealStationIdAndTitle(stationId, company.getTitle());
            if (companyByTitle != null && companyByTitle.getId().longValue() != company.getId().longValue()
                    && companyStatus.equals(companyByTitle.getCompanyStatus())) {
                throw new UniqueConstraintsException("已存在名称为" + company.getTitle() + "的企业");
            }
        }

    }

    /**
     * 新增企业
     * @param company 企业对象
     */
    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public Company createCompany(Company company, Long stationId)
            throws ArgumentErrorException, UniqueConstraintsException, ObjectNotFoundException, PinyinException, ModelNotFoundException {
        company.setId(null);
        RealStation station = realStationService.findById(stationId);
        if (station == null) {
            throw new ObjectNotFoundException("找不到Id为" + stationId + "的电站");
        }
        company.setCreatTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        company.setCompanyStatus("0");
        company.setSn(PinyinHelper.getShortPinyin(company.getTitle()).toUpperCase());
        company.setCreatTime(DateTimeUtils.format(DateTimeUtils.PATTERN.DATETIME.value(),new Date()));
        processBeforeSave(company, stationId);

        List<Office> offices = company.getOffices();
        if (CollectionUtil.isNotEmpty(offices)) {
            List<String> alreadyBindOffices = new ArrayList<>();
            offices.forEach(office -> {
                Office officeById = officeService.findById(office.getId());
                if (officeById != null &&
                        !OfficeConts.OFFICE_STATUS_CODE.Vacant.value().equals(officeById.getOfficeStatus())) {
                    alreadyBindOffices.add(officeById.getOfficeTitle());
                    //招商管理成功项目同步到在园企业
                    if(officeById.getSettledCompanyId() != null && company.getIntentionId() != null
                            && officeById.getSettledCompanyId().longValue() == company.getIntentionId().longValue()){
                        alreadyBindOffices.remove(officeById.getOfficeTitle());
                    }

                }
            });
            if (CollectionUtil.isNotEmpty(alreadyBindOffices)) {
                throw new ArgumentErrorException(alreadyBindOffices.toString() + "不是空置厂房，请确认");
            }
        }

        //这一步是防止实体类中的office也被更新导致状态设置为空
        company.setOffices(null);
        Company newCompany = companyCrudRepository.save(company);
        //绑定Station
        realStationService.realStationBindCompany(station.getId(), newCompany.getId());
        //如果新导入的厂房之前存在，就更新，不存在就为公司添加厂房。
        if(!CollectionUtil.isEmpty(offices)){
            //通过电站ID 和厂房名称查询当前电站下是否存在对应的厂房信息
            for (Office office : offices) {
                Office officeByStationId = officeService.findByRealStationIdAndOfficeTitle(stationId,office.getOfficeTitle());
                if(officeByStationId != null){

                    //更新厂房状态
                    officeByStationId.setOfficeStatus("03");
                    officeByStationId.setCompanyName(newCompany.getTitle());
                    officeByStationId.setCompanyId(newCompany.getId());
                    officeService.updateOffice(officeByStationId);

                    officeService.bindCompany(newCompany.getId(),officeByStationId.getId());
                }
            }
        }

        //这边同步创建一个企业超管的角色
        Role role = new Role();
        role.setName("superManager");
        role.setTitle("超级管理员");
        role.setDescription("系统自动生成的超级管理员");
        companyRoleService.createRole(newCompany.getId(), role);


        return newCompany;
    }

    @Override
    public String intentionToCompany(Long intentionId, String officeIds, String title, String leaseTime, String leaseDueTime,
                                     List<ContractAccessories> contractAccessoriesList)
            throws ArgumentErrorException, UniqueConstraintsException, ObjectNotFoundException, PinyinException, ModelNotFoundException {
        String message = "success";
        List<Office> officeList = new ArrayList<>();

        Double area = (double) 0;
        Company company = new Company();
        Long realStationId = null;
        if (StringUtils.isNotEmpty(officeIds)) {
            String[] idSplit = officeIds.split(",");
            for (String id : idSplit) {
                Office office = officeService.findById(Long.valueOf(id));
                area += office.getOfficeArea();
                officeList.add(office);
            }
            //需要根据厂房查询厂房所在真实园区
            RealStation realStation = realStationService.findRealStationByOfficeId(Long.valueOf(idSplit[0]));
            realStationId = realStation.getId();

            company.setTitle(title);
            company.setIntentionId(intentionId);
            company.setLeaseTime(leaseTime);
            company.setLeaseStartTime(leaseTime);
            company.setLeaseEndTime(leaseDueTime);
            //company.setLeaseDueTime(leaseDueTime);
            company.setOffices(officeList);
            company.setArea(area);
            try {
                Company company1 = createCompany(company, realStationId);
                createCompanyContract(company1,contractAccessoriesList);
            }catch (ArgumentErrorException e){
                message = "error-"+e.getMessage();
            } catch (ObjectNotFoundException e){
                message = "error-"+e.getMessage();
            }catch (PinyinException e){
                message = "error-"+"企业名称转换拼音缩写异常！";
            }
            log.debug(message);
        }
        return message;
    }

    private void createCompanyContract(Company company1, List<ContractAccessories> contractAccessoriesList) {
        if(CollectionUtil.isNotEmpty(contractAccessoriesList)){
            for (ContractAccessories contractAccessories : contractAccessoriesList) {
                User byUserId = userService.findByUserId(Long.valueOf(contractAccessories.getContractor()));
                if(byUserId != null){
                    contractAccessories.setContractor(byUserId.getTitle());
                }
                paymentInfoService.createContract(company1.getId(),contractAccessories);
            }
        }
    }


    /**
     * 根据Id删除企业
     * @param ids 企业ID
     */
    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public void deleteCompany(String ids)
            throws ObjectNotFoundException, ModelNotFoundException, ArgumentErrorException, UniqueConstraintsException {
        String[] idList = ids.split(",");
        for (String id : idList) {
            //判断企业是否存在
            Company companyById = this.findById(Long.valueOf(id));
            if (companyById != null) {
                //这边需要将绑定的厂房设置成空置的
                Iterable<Office> offices = officeService.findByCompanyId(Long.valueOf(id));
                if (offices.iterator().hasNext()) {
                    for (Office office : offices) {
                        //更新厂房状态
                        office.setOfficeStatus(OfficeConts.OFFICE_STATUS_CODE.Vacant.value());
                        office.setCompanyName(null);
                        office.setCompanyId(null);
                        officeService.updateOffice(office);
                    }
                }
                //解绑并删除企业缴费信息、合同附件
                paymentInfoService.unbindDeleteCompanyPaymentInfo(Long.valueOf(id));
                //解绑并删除企业配套信息
                companySupportingInfoService.unbindAndDelete(Long.valueOf(id));
                //这里直接删除
                companyCrudRepository.deleteById(Long.valueOf(id));
            } else {
                throw new ObjectNotFoundException("找不到Id为" + id +"的企业");
            }
        }
    }

    /**
     * 更新企业（更新全部字段）
     * @param company 企业对象
     */
    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public Company updateCompany(Company company)
            throws ArgumentErrorException, UniqueConstraintsException, ObjectNotFoundException {
        Optional<Company> companyOptional = companyCrudRepository.findById(company.getId());
        if (!companyOptional.isPresent()) {
            throw new ObjectNotFoundException("找不到ID为" + company.getId() + "的企业");
        }

        Company oldCompany = companyOptional.get();
        Optional.of(company.getArea()).ifPresent(oldCompany::setArea);
        Optional.ofNullable(company.getAbbreviation()).ifPresent(oldCompany::setAbbreviation);
        Optional.ofNullable(company.getChargePerson()).ifPresent(oldCompany::setChargePerson);
        Optional.ofNullable(company.getChargePersonPhone()).ifPresent(oldCompany::setChargePersonPhone);
        Optional.ofNullable(company.getCode()).ifPresent(oldCompany::setCode);
        Optional.ofNullable(company.getCompanyAdministrativeRegions()).ifPresent(oldCompany::setCompanyAdministrativeRegions);
        Optional.ofNullable(company.getCompanyRegisteredAddress()).ifPresent(oldCompany::setCompanyRegisteredAddress);
        Optional.ofNullable(company.getCompanyStatus()).ifPresent(oldCompany::setCompanyStatus);
        Optional.ofNullable(company.getEmailAddress()).ifPresent(oldCompany::setEmailAddress);
        Optional.ofNullable(company.getLeaseDueTime()).ifPresent(oldCompany::setLeaseDueTime);
        Optional.ofNullable(company.getLeaseEndTime()).ifPresent(oldCompany::setLeaseEndTime);
        Optional.ofNullable(company.getLeaseStartTime()).ifPresent(oldCompany::setLeaseStartTime);
        Optional.ofNullable(company.getLeaseTime()).ifPresent(oldCompany::setLeaseTime);
        Optional.ofNullable(company.getLegalPerson()).ifPresent(oldCompany::setLegalPerson);
        Optional.ofNullable(company.getName()).ifPresent(oldCompany::setName);
        Optional.ofNullable(company.getOffices()).ifPresent(oldCompany::setOffices);
        Optional.ofNullable(company.getOperatingPeriod()).ifPresent(oldCompany::setOperatingPeriod);
        Optional.ofNullable(company.getPaymentDate()).ifPresent(oldCompany::setPaymentDate);
        Optional.ofNullable(company.getPersonPosition()).ifPresent(oldCompany::setPersonPosition);
        Optional.ofNullable(company.getRegisteredCapital()).ifPresent(oldCompany::setRegisteredCapital);
        Optional.ofNullable(company.getRegistrationTime()).ifPresent(oldCompany::setRegistrationTime);
        Optional.ofNullable(company.getTitle()).ifPresent(title -> {
            oldCompany.setTitle(title);
            syncUpdateOfficeCompanyName(oldCompany, title);
        });
        Optional.ofNullable(company.getTypeOfEnterprise()).ifPresent(oldCompany::setTypeOfEnterprise);
        Optional.ofNullable(company.getUnifiedSocialCreditCode()).ifPresent(oldCompany::setUnifiedSocialCreditCode);
        Optional.ofNullable(company.getAreaAddress()).ifPresent(oldCompany::setAreaAddress);
        Optional.ofNullable(company.getAreaAddressTitle()).ifPresent(oldCompany::setAreaAddressTitle);

        //在园企业状态
        String companyStatus = "0";
        String stationId = ServerContextHolder.getContext().getProjectCode();
        Company companyByTitle = companyCrudRepository.findByStationAndTitle(Long.valueOf(stationId), company.getTitle());
        if (companyByTitle != null && companyByTitle.getId().longValue() != company.getId().longValue()
                && companyStatus.equals(companyByTitle.getCompanyStatus())) {
            throw new UniqueConstraintsException("已存在名称为" + company.getTitle() + "的企业");
        }
        oldCompany.setOffices(null);
        //先更新
        Company newCompany = companyCrudRepository.save(oldCompany);
//        newCompany.setOffices(company.getOffices());
//
//        if (CollectionUtil.isNotEmpty(company.getOffices())) {
//            //先解绑再绑定
//            officeService.unbindCompany(oldCompany.getId());
//            company.getOffices().forEach(office -> {
//                officeService.bindCompany(oldCompany.getId(), office.getId());
//            });
//        }

        return newCompany;
    }

    //同步更新厂房中的企业名称字段
    private void syncUpdateOfficeCompanyName(Company company, String title) {
        try {
            Iterable<Office> offices = officeService.findByCompanyId(company.getId());
            for (Office office : offices) {
                office.setCompanyName(title);
                officeService.updateOffice(office);
            }
        } catch (ObjectNotFoundException | UniqueConstraintsException e) {
            e.printStackTrace();
        }
    }


    /**
     * 根据ID获得企业
     * @param id 企业ID
     */
    @Override
    public Company findById(Long id) throws ObjectNotFoundException {
        Company company = new Company();
        Optional<Company> optionalCompany = companyCrudRepository.findById(id);
        if (optionalCompany.isPresent()) {
            company = optionalCompany.get();
            //查询厂房
            List<Office> offices = (List<Office>)officeService.findByCompanyId(id);
            if (CollectionUtil.isNotEmpty(offices)) {
                company.setOffices(offices);
            }
            //查询绑定的真实园区id
            RealStation realStation = realStationService.findRealStationByCompanyId(id);
            if (realStation != null) {
                company.setReadStationId(realStation.getId());
                company.setStationTitle(realStation.getAbbreviationName());
            }
        }
        return company;
    }


    public Company findByName(String name) {
        return companyCrudRepository.findByName(name);
    }

    /**
     * 根据code获得企业
     * @param code 企业code
     */
    @Override
    public Company findByCode(Long code) {
        return companyCrudRepository.findByCode(code);
    }

    @Override
    public Company findByUnifiedSocialCreditCode(String unifiedSocialCreditCode) {
        return companyCrudRepository.findByUnifiedSocialCreditCode(unifiedSocialCreditCode);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public void upload(List<CompanyUpload> companyUploadList) throws ObjectNotFoundException, UniqueConstraintsException, ArgumentErrorException, PinyinException, ModelNotFoundException {
        for (CompanyUpload companyUpload : companyUploadList) {
            //将导入模板的值转化为Company模型
            Company company = convertToCompany(companyUpload);
            //通过电站title查询电站是否存在
            Station stationByTitle = stationService.findByEnterpriseFullName(company.getStationTitle());
            if (stationByTitle == null) {
                throw new ObjectNotFoundException("找不到名称为" + company.getStationTitle() + "的电站");
            }
            //通过公司code查询这个公司是不是已经在库中存在了
            Company companyByCode = this.findByCode(company.getCode());
            //如果不存在就新建这个company模型，绑定对应的园区和厂房.
            if (companyByCode == null) {
                this.createCompany(company, stationByTitle.getId());
            } else {
                company.setId(companyByCode.getId());
                //如果库中已经有该company模型，先判断归属的电站是否一致，不一致就绑定新的
                Station station = stationService.findStationByBindCompanyId(companyByCode.getId());
                if (station != null) {
                    if (!stationByTitle.getEnterpriseFullName().equals(station.getEnterpriseFullName())) {
                        stationService.unbindCompany(station.getId(), company.getId());
                        stationService.bindCompany(stationByTitle.getId(), company.getId());
                    }
                }else {
                    stationService.bindCompany(stationByTitle.getId(), company.getId());
                }
                //如果新导入的厂房之前存在，就更新，不存在就为公司添加厂房。
                List<Office> officesByCompanyId = (List<Office>) officeService.findByCompanyId(company.getId());
                List<Office> offices = company.getOffices();
                String officeName = offices.get(0).getOfficeName();
                if (CollectionUtil.isEmpty(offices)) {
                    company.setOffices(new ArrayList<>());
                }
                if(CollectionUtil.isNotEmpty(officesByCompanyId)){
                    List<String> collect = officesByCompanyId.stream().map(office -> {
                        return office.getOfficeName();
                    }).collect(Collectors.toList());
                    //判断之前企业绑定的厂房是否包含当前厂房 如果不包含 当前厂房 则 再判断 当前厂房在当前电站是否存在
                    // 如果存在加入绑定企业的厂房list 如果不存在新建厂房与电站绑定，在加入之前绑定企业的厂房信息
                    if(!collect.contains(officeName)){
                        Office office1 = officeService.findByStationIdAndOfficeName(station.getId(),officeName);
                        if(office1 == null){
                            //创建厂房
                            Office newoffice = officeService.createOfficeByStationId(stationByTitle.getId(), offices.get(0));
                            officesByCompanyId.add(newoffice);
                        }else {
                            officesByCompanyId.add(office1);
                        }
                    }
                }
                company.setOffices(null);
                //将公司信息更新
                companyrepository.unbindAllOffice(company.getId());
                companyCrudRepository.save(company);
                //循环绑定
                for (Office office : officesByCompanyId) {
                    officeService.bindCompany(company.getId(),office.getId());
                }
            }
        }
    }

    @Override
    public Page<CompanyUpload> findAllForPage(PageParam pageParam) {
        List<String> sortList = pageParam.getSort();
        if (sortList == null) {
            sortList = new ArrayList<>();
        }
        sortList.add("leaseTime");
        pageParam.setSort(sortList);
        companyCrudRepository.castStaffCount();
            Pageable pageable = PageRequest.of(pageParam.getPage()-1, pageParam.getSize());
            Page<CompanyUpload> companyUploads = companyrepository.findAllForPage(pageParam);
            return companyUploads;
       // return companyCrudRepository.findAllForPage(pageParam.getPage()* pageParam.getSize(),pageParam.getSize());
    }

    @Override
    public Page<Company> findStationAllCompanyForPage(String searchKey, Long stationId, PageParam pageParam) {

        Pageable pageable = PageRequest.of(pageParam.getPage() - 1, pageParam.getSize());

        List<String> sortList = pageParam.getSort();
        if (sortList == null) {
            sortList = new ArrayList<>();
        }
        sortList.add("leaseTime");
        pageParam.setSort(sortList);
        Page<Company> companies = companyrepository.findCompaniesByRealStationId(searchKey, stationId, pageParam);
        //这边如果是空那么这个园区可能为总园区，直接用总园区id查
        if (companies.isEmpty()) {
            companies = companyrepository.findCompaniesByStationId(searchKey, stationId, pageParam);
        }
        return companies;
    }

    @Override
    public void export(String ids, Long exportPeopleId , HttpServletResponse httpServletResponse) throws UniqueConstraintsException {
        List<CompanyUpload> data = new ArrayList<>();
        String[] split = ids.split(",");
        for(String idString : split){
            Long id = Long.parseLong(idString);
            Company companyByOfficeId = companyCrudRepository.findByOfficeId(id);
            Office officeById = officeService.findById(id);
            if (companyByOfficeId != null && officeById != null){
                CompanyUpload companyUpload = convertToEnterpriseUpload(companyByOfficeId,officeById);
                officeById.setExportPeople(exportPeopleId);
                officeById.setExportCount(officeById.getExportCount()+1);
                officeService.updateOffice(officeById);
                data.add(companyUpload);
            }
        }
        if (!CollectionUtil.isEmpty(data)){
            ExcelUtils.export(data,httpServletResponse,CompanyUpload.class);
        }
    }

    @Override
    public Iterable<Company> findByRealStationId(Long realStationId) {
        return companyCrudRepository.findByRealStationId(realStationId);
    }

    @Override
    public Iterable<Company> findByRealStationId(Long id, String type) {
        return companyCrudRepository.findByRealStationIdAndStatus(id,type);
    }

    @Override
    public void downCompanyUploadTemplate(Long exportPeopleId, HttpServletResponse response) throws IOException {
        Map<String, List<String>> data = new HashMap<>();
        //获取项目id
        String projectCode = ServerContextHolder.getContext().getProjectCode();
        //数据处理
        if(!StringUtil.isEmpty(projectCode)){
            Long stationId = Long.valueOf(projectCode);
            Iterable<RealStation> realStations = realStationService.findRealStationByStationId(stationId);
            if(realStations != null){
                for (RealStation realStation : realStations) {
                    //真实园区查询厂房信息
                    List<String> officeNames = new ArrayList<>();
                    Iterable<Office> offices = officeService.findOfficesByRealStationId(realStation.getId());
                    if(offices != null){
                        for (Office office : offices) {
                            officeNames.add(office.getOfficeTitle());
                        }
                    }
                    data.put(StringUtil.isEmpty(realStation.getAbbreviationName()) ?
                            realStation.getEnterpriseFullName() : realStation.getAbbreviationName(),CollectionUtil.isNotEmpty(officeNames)?officeNames:Arrays.asList("无厂房信息"));
                }
            }
        }else {
            Iterable<RealStation> realStations =  realStationService.findAll();
            if(realStations != null){
                for (RealStation realStation : realStations) {
                    //真实园区查询厂房信息
                    List<String> officeNames = new ArrayList<>();
                    Iterable<Office> offices = officeService.findOfficesByRealStationId(realStation.getId());
                    if(offices != null){
                        for (Office office : offices) {
                            officeNames.add(office.getOfficeTitle());
                        }
                    }
                    data.put(StringUtil.isEmpty(realStation.getAbbreviationName()) ?
                                realStation.getEnterpriseFullName() : realStation.getAbbreviationName(),CollectionUtil.isNotEmpty(officeNames)?officeNames:Arrays.asList("无厂房信息"));

                }
            }
        }
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = resolver.getResources("classpath:company/export-template.xls");
        Resource resource = resources[0];
        InputStream inputStream = resource.getInputStream();
        // 获取模板文件
        //File fi = resource.getFile();
        POIFSFileSystem fs = new POIFSFileSystem(inputStream);
        //读取excel模板
        HSSFWorkbook workbook = new HSSFWorkbook(fs);
        //读取模板内所有sheet内容
        HSSFSheet excelSheet = workbook.getSheetAt(0);
        PoiUtils.addValidationToSheet(workbook, excelSheet, data, 'B', 'C', 2, 10000);
        // 隐藏存储下拉列表数据的sheet；可以注释掉该行以便查看、理解存储格式
        PoiUtils.hideTempDataSheet(workbook, 1);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        workbook.write(os);
        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + URLEncoder.encode("企业信息批量导入模板.xlsx", "utf-8"));
        ServletOutputStream sout = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(sout);
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (Exception e) {
            log.error("企业信息批量导入模板初始化失败:", e);
        } finally {
            if (bis != null) {
                bis.close();
            }
            if (bos != null) {
                bos.close();
            }
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public void importCompanyExcel(List<CompanyPoi> list) throws ObjectNotFoundException, PinyinException, ModelNotFoundException, ArgumentErrorException, UniqueConstraintsException {

        String stationId = ServerContextHolder.getContext().getProjectCode();
        // 导入
        for (CompanyPoi companyPoi : list) {
            log.info("开始导入数据>>>>>>>>>> " + companyPoi.toString());
            //根据归属园区title反查归属园区
            Company company = new Company();
            List<Office> officeList = new ArrayList<>();
            //stationTitle必须传真实园区简称
            RealStation realStation = realStationService.findRealStationByStationIdAndAbbreviationName(Long.valueOf(stationId), companyPoi.getStationTitle());
            if (realStation == null) {
                log.info(companyPoi.getStationTitle() + "未找到该园区");
                continue;
            }
            log.info("查询到真实园区：{}", realStation.getAbbreviationName());

            //根据归属园区ID与厂房title反查厂房
            Office office = officeService.findOfficeByStationIdAndTitle(Long.valueOf(stationId), companyPoi.getOfficeTitle());
            if (office == null) {
                log.info(companyPoi.getOfficeTitle() + "未找到该房源");
                continue;
            }
            log.info("查询到厂房：{}", office.getOfficeTitle());

            BeanUtils.copyProperties(companyPoi, company);
            officeList.add(office);
            company.setOffices(officeList);

            //给company赋值 入库
            createCompanyForImport(company, realStation.getId());
        }
    }

    @Override
    public void exportNew(String ids, HttpServletResponse response)
            throws ObjectNotFoundException {
        List<CompanyPoi> vos = new ArrayList<>();

        String[] idsStr = ids.split(",");
        for (String id : idsStr) {
            Company company = companyrepository.findById(Long.valueOf(id));
            Iterable<Office> offices = officeService.findByCompanyId(Long.valueOf(id));
            while (offices.iterator().hasNext()) {
                CompanyPoi poi = new CompanyPoi();
                Office office = offices.iterator().next();
                BeanUtils.copyProperties(company, poi);
                poi.setOfficeTitle(office.getOfficeTitle());
                vos.add(poi);
            }
            if (!offices.iterator().hasNext()) {
                CompanyPoi poi = new CompanyPoi();
                BeanUtils.copyProperties(company, poi);
                vos.add(poi);
            }
        }
        ExcelUtils.export(vos,response,CompanyPoi.class);
    }

    @Override
    public void companyLeave(Long companyId) throws ObjectNotFoundException, ArgumentErrorException, ModelNotFoundException, UniqueConstraintsException {
        Company existCompany = companyrepository.findById(companyId);
        if (existCompany == null) {
            throw new ObjectNotFoundException("企业未找到");
        }
        String leaveCompanyStatus = "1";
        if (leaveCompanyStatus.equals(existCompany.getCompanyStatus())) {
            throw new ArgumentErrorException("企业已离场，请勿重复操作");
        }
        existCompany.setCompanyStatus(leaveCompanyStatus);
        //更新企业状态
        Company newCompany = companyCrudRepository.save(existCompany);

        Iterable<Office> offices = officeService.findByCompanyId(companyId);
        for (Office office : offices) {
            //更新厂房状态 设置为空置
            office.setOfficeStatus(OfficeConts.OFFICE_STATUS_CODE.Vacant.value());
            office.setCompanyName(null);
            office.setCompanyId(null);
            officeService.updateOffice(office);
        }

        //解绑厂房
        officeService.unbindCompany(companyId);

    }

    @Override
    public List<Company> findAll() {
        return companyCrudRepository.findByCompanyStatus("0");
    }

    @Override
    public Company findByEmployeeId(Long employeeId) {
        return companyCrudRepository.findByEmployeeId(employeeId);
    }

    @Override
    public List<Company> findCompanyByRealStationId(Long stationId) {
        return companyCrudRepository.findCompanyByRealStationId(stationId);
    }

    @Override
    public OfficeManageCompanyInfoVO getCompanyInfoByOfficeId(Long officeId){
        OfficeManageCompanyInfoVO officeManageCompanyInfoVO = new OfficeManageCompanyInfoVO();
        Office office = officeService.findById(officeId);
        if (office.getCompanyId() == null){
            //该房源没有企业入驻,返回null
            return null;
        }
        Company company = companyrepository.findById(office.getCompanyId());
        if (company != null){
            BeanUtils.copyProperties(company, officeManageCompanyInfoVO);
        }
        CompanySupportingInfo companySupportingInfo = companySupportingInfoService.getByCompanyId(company.getId());
        if (companySupportingInfo != null){
            officeManageCompanyInfoVO.setEnterpriseScale(companySupportingInfo.getEnterpriseScale());
            officeManageCompanyInfoVO.setIndustry(companySupportingInfo.getIndustry());
            officeManageCompanyInfoVO.setProduct(companySupportingInfo.getProduct());
        }
        return officeManageCompanyInfoVO;
    }

    private void createCompanyForImport(Company company, Long realStationId)
            throws PinyinException, ModelNotFoundException, ArgumentErrorException, UniqueConstraintsException, ObjectNotFoundException {

        boolean isNewCompany = false;

        RealStation station = realStationService.findById(realStationId);
        List<Office> offices = company.getOffices();

        company.setSn(PinyinHelper.getShortPinyin(company.getTitle()).toUpperCase());
        //判断电站下企业名称是否重复
        Company companyByTitle = companyCrudRepository.findByRealStationIdAndTitle(realStationId, company.getTitle());
        if (companyByTitle != null) {
            //这边代表此企业已经存在，那么把ID拿过来更新这个企业
            company.setId(companyByTitle.getId());
            log.info("{}--企业已存在", company.getTitle());
        } else {
            isNewCompany = true;
        }

        company.setCreatTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        company.setCompanyStatus("0");

        company.setOffices(null);
        Company newCompany = companyCrudRepository.save(company);

        //绑定RealStation 未绑定过的需要去绑定
        Company companyBindRealStation = companyCrudRepository.findByRealStationIdAndCompanyId(realStationId, newCompany.getId());
        if (companyBindRealStation == null) {
            log.info("{}--企业去绑定真实园区", company.getTitle());
            realStationService.realStationBindCompany(station.getId(), newCompany.getId());
        }

        //如果新导入的厂房之前存在，才绑定
        if (!CollectionUtil.isEmpty(offices)) {
            //通过真实园区ID 和厂房名称查询当前电站下是否存在对应的厂房信息
            for (Office office : offices) {
                Office officeByStationId = officeService.findByRealStationIdAndOfficeTitle(realStationId, office.getOfficeTitle());
                if (officeByStationId != null && "01".equals(officeByStationId.getOfficeStatus()) ) {
                    log.info("{}--厂房存在该真实园区下并且为空置状态", officeByStationId.getOfficeTitle());
                    //这边还有，如果已绑定过的房源不再进行重复绑定，需要判断此房源是否已经跟此企业绑定
                    Office officeIsBind = officeService.findByCompanyIdAndOfficeId(newCompany.getId(), officeByStationId.getId());
                    if (officeIsBind == null) {
                        log.info("{}--厂房未绑定过，开始绑定", officeByStationId.getOfficeTitle());
                        //更新厂房状态 已租
                        officeByStationId.setOfficeStatus(OfficeConts.OFFICE_STATUS_CODE.Rented.value());
                        officeByStationId.setCompanyName(newCompany.getTitle());
                        officeByStationId.setCompanyId(newCompany.getId());
                        officeService.updateOffice(officeByStationId);

                        officeService.bindCompany(newCompany.getId(), officeByStationId.getId());
                    }
                }
            }
        }

        //这边去更新该企业的面积
        Iterable<Office> officeIterable = officeService.findByCompanyId(newCompany.getId());
        double area = 0;
        for (Office office : officeIterable) {
            area += office.getOfficeArea();
        }
        newCompany.setArea(area);
        newCompany.setOffices(null);
        companyCrudRepository.save(newCompany);

        //如果是新的企业还需要同步创建超管角色
        if (isNewCompany) {
            //这边同步创建一个企业超管的角色
            Role role = new Role();
            role.setName("superManager");
            role.setTitle("超级管理员");
            role.setDescription("系统自动生成的超级管理员");
            companyRoleService.createRole(newCompany.getId(), role);
        }

        log.info("{}--企业导入完毕", company.getTitle());
    }


    /**
     * 根据条件获得所有企业列表
     * @param firmId 单位ID
     * @param stationId 电站ID
     */
    @Override
    public List<Company> getCompanys(Long firmId, Long stationId) {
        if (stationId != null) {
            return findByStationId(stationId);
        } else if (firmId != null) {
            return findByFirmId(firmId);
        } else {
            return companyrepository.findAll();
        }
    }

    private Company convertToCompany(CompanyUpload companyUpload) {
        Company company = new Company();
        BeanUtils.copyProperties(companyUpload,company);
        company.setTitle(companyUpload.getName());
        company.setCode(Long.parseLong(companyUpload.getBusinessRegistrationNumber()));
//        if (!StringUtil.isEmpty(company.getBuildingNumber()) ){
//            Office office =new Office();
//            office.setLeaseDueTime(companyUpload.getLeaseDueTime());
//            office.setLeasePrice(companyUpload.getLeasePrice());
//            office.setLeaseTime(companyUpload.getLeaseTime());
//            office.setOfficeName(companyUpload.getBuildingNumber());
//            office.setOfficeTitle(companyUpload.getBuildingNumber());
//            office.setOfficeArea(Double.parseDouble(companyUpload.getArea()));
//            company.setOffices(Arrays.asList(office));
//        }
        return company;
    }

    private CompanyUpload convertToEnterpriseUpload(Company company , Office office){
            CompanyUpload companyUpload = new CompanyUpload();
            BeanUtils.copyProperties(company,companyUpload);
            companyUpload.setBuildingNumber(office.getOfficeName());
            companyUpload.setArea(String.valueOf(office.getOfficeArea()));
            companyUpload.setLeaseDueTime(office.getLeaseDueTime());
            companyUpload.setLeasePrice(office.getLeasePrice());
            companyUpload.setLeaseTime(office.getLeaseTime());
        return companyUpload;
    }

}
